import {
  _decorator,
  Component,
  Prefab,
  Node,
  instantiate,
  Vec3,
  UITransform,
  Input,
  RigidBody2D,
  view,
  EventTouch,
  AudioClip,
} from 'cc'
import { Block } from './Block'
import { DataManager } from './DataManager'
import { AudioMgr } from './Utils/AudioMgr'
import { GAME_STATUS_ENUM } from './Enums'
import { GAME_STATUS } from './Events'
const { ccclass, property } = _decorator

@ccclass('BlockManager')
export class BlockManager extends Component {
  @property(Prefab)
  blockPrefab: Prefab = null!
  @property(AudioClip)
  dropSound: AudioClip = null!
  @property(Node)
  blockNodes: Node = null!

  private minX = 0
  private maxX = 0
  private isDragging = false
  private isDropping = false // 是否处于物理掉落中
  // 拖动块节点
  private blockNode: Node = null!
  // 拖动块刚体
  private blockRigidBody: RigidBody2D = null
  // 块极限值
  private failThresholdY = 600

  protected onLoad(): void {
    DataManager.inst.blockPrefab = this.blockPrefab
    GAME_STATUS.on(GAME_STATUS_ENUM.RUNNING, this.reStart, this)
  }
  protected start(): void {
    this.spawnNextBlock()
  }
  spawnNextBlock() {
    this.node.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
    this.node.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
    this.node.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
    const currentWord = DataManager.inst.currentWord()
    this.blockNode = instantiate(this.blockPrefab)
    const blockScript = this.blockNode.getComponent(Block)!
    blockScript.status = 'static'
    blockScript.word = currentWord.word
    blockScript.mergeWord = currentWord.mergeWord
    this.blockNode.setPosition(new Vec3(0, 350, 0))
    this.blockNodes.addChild(this.blockNode)

    const containerWidth = view.getVisibleSize().width
    const blockUI = this.blockNode.getComponent(UITransform)
    const blockWidth = blockUI.width
    this.failThresholdY =
      this.node.getComponent(UITransform).height / 2 - blockUI.height * 2

    const halfRange = (containerWidth - blockWidth) / 2

    this.minX = -halfRange
    this.maxX = halfRange

    this.scheduleOnce(() => {
      this.blockRigidBody = this.blockNode.getComponent(RigidBody2D)
      if (this.blockRigidBody) {
        this.blockRigidBody.enabled = false
      } else {
        console.warn('RigidBody2D 获取失败')
      }
    }, 0)
  }

  onTouchStart(event: EventTouch) {
    if (this.isDropping) return // 掉落中不能再拖
    this.isDragging = true

    // 获取手指在容器本地坐标中的位置
    const uiPos = event.getUILocation()
    const localTouch = new Vec3(uiPos.x, uiPos.y, 0)
    this.node.getComponent(UITransform).convertToNodeSpaceAR(localTouch, localTouch)

    // 将滑块位置的 X 直接设置为触点 X，Y 保持不变
    const newX = Math.max(this.minX, Math.min(this.maxX, localTouch.x))
    const pos = this.blockNode.getPosition()
    this.blockNode.setPosition(newX, pos.y, pos.z)
  }

  onTouchMove(event: EventTouch) {
    if (!this.isDragging) return

    const uiPos = event.getUILocation()
    const localTouch = new Vec3(uiPos.x, uiPos.y, 0)
    this.node.getComponent(UITransform).convertToNodeSpaceAR(localTouch, localTouch)

    const newX = Math.max(this.minX, Math.min(this.maxX, localTouch.x))
    const pos = this.blockNode.getPosition()
    this.blockNode.setPosition(newX, pos.y, pos.z)
  }

  onTouchEnd() {
    this.node.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
    this.node.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
    this.node.off(Input.EventType.TOUCH_END, this.onTouchEnd, this)
    if (this.isDragging) {
      this.blockRigidBody.enabled = true
      this.isDropping = true
    }
    if (DataManager.inst.completedIdioms.length !== DataManager.inst.idioms.length) {
      this.scheduleOnce(() => {
        this.isDropping = false
        this.spawnNextBlock()
      }, 0.4)
    }
  }

  checkGameOver(blockNode) {
    // 获取当前场上所有 Block 节点
    const allBlocks = this.blockNodes.children.filter(
      n => n.name.includes('Block') && n !== blockNode,
    )
    let maxY = 0
    for (const block of allBlocks) {
      const y = block.position.y
      if (y > maxY) {
        maxY = y
      }
    }
    if (maxY >= this.failThresholdY) {
      this.onGameOver()
    }
  }

  onGameOver() {
    // 显示 Complete 面板
    DataManager.inst.gameStatus = GAME_STATUS_ENUM.LOSED
    GAME_STATUS.emit(GAME_STATUS_ENUM.LOSED)
  }
  // 重新开始后清除节点
  reStart() {
    this.isDragging = false
    this.isDropping = false
    // 分析这里为什么报错
    this.blockNodes.removeAllChildren()
    this.spawnNextBlock()
  }
  onDestroy() {
    this.node.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
    this.node.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
    this.node.off(Input.EventType.TOUCH_END, this.onTouchEnd, this)
  }
}
